<?php

namespace App\Pool\Database;


use Illuminate\Foundation\Application;
use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;

class DbPool
{
    protected $app;

    protected $pool;

    public function __construct(Application $app)
    {
        $this->app = $app;
        $this->init();
    }

    /**
     * 创建连接池，如果需要连接多个库，将$config换成数组形式，下边在foreach中创建
     * .env文件中需要配置好下边的一些参数，DB_SIZE是连接池中连接的数量
     */
    protected function init()
    {
        $config = (new PDOConfig())
            ->withHost(env('DB_HOST', '127.0.0.1'))
            ->withPort(env('DB_PORT', 3306))
            ->withDbname(env('DB_DATABASE', 'laravel'))
            ->withUsername(env('DB_USERNAME', 'root'))
            ->withPassword(env('DB_PASSWORD', 'root'));

        $this->pool = new PDOPool($config, env('DB_SIZE', 20));
    }

    public function get()
    {
        return $this->pool->get();
    }

    public function put($pdo)
    {
        $this->pool->put($pdo);
    }
}